<template>
  <div class="shopping-cart-example">
    <h2>🛒 购物车示例 - Modules模块化管理</h2>
    
    <div class="cart-container">
      <!-- 商品展示区 -->
      <div class="products-section">
        <h3>📚 商品列表</h3>
        <div class="products-grid">
          <div 
            v-for="product in availableProducts" 
            :key="product.id"
            class="product-card"
          >
            <div class="product-info">
              <h4>{{ product.name }}</h4>
              <p class="product-price">¥{{ product.price }}</p>
              <p class="product-inventory">库存: {{ product.inventory }}</p>
            </div>
            <div class="product-actions">
              <div class="quantity-selector">
                <button 
                  @click="decreaseQuantity(product.id)"
                  :disabled="getSelectedQuantity(product.id) <= 1"
                  class="btn btn-small"
                >
                  -
                </button>
                <span class="quantity-display">{{ getSelectedQuantity(product.id) }}</span>
                <button 
                  @click="increaseQuantity(product.id)"
                  :disabled="getSelectedQuantity(product.id) >= product.inventory"
                  class="btn btn-small"
                >
                  +
                </button>
              </div>
              <button 
                @click="addToCart(product.id)"
                :disabled="product.inventory === 0"
                class="btn btn-primary"
              >
                {{ product.inventory === 0 ? '缺货' : '加入购物车' }}
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 购物车区域 -->
      <div class="cart-section">
        <div class="cart-header">
          <h3>🛍️ 购物车 ({{ cartItemCount }}件商品)</h3>
          <button 
            v-if="!isCartEmpty"
            @click="clearCart"
            class="btn btn-secondary btn-small"
          >
            清空购物车
          </button>
        </div>
        
        <div v-if="isCartEmpty" class="empty-cart">
          <p>购物车是空的</p>
          <p>去上面选择一些商品吧！</p>
        </div>
        
        <div v-else class="cart-items">
          <div 
            v-for="item in cartItems" 
            :key="item.id"
            class="cart-item"
          >
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <p class="item-price">单价: ¥{{ item.price }}</p>
            </div>
            <div class="item-controls">
              <div class="quantity-controls">
                <button 
                  @click="updateItemQuantity(item.id, item.quantity - 1)"
                  class="btn btn-small"
                >
                  -
                </button>
                <span class="quantity">{{ item.quantity }}</span>
                <button 
                  @click="updateItemQuantity(item.id, item.quantity + 1)"
                  :disabled="!canIncreaseQuantity(item.id, item.quantity)"
                  class="btn btn-small"
                >
                  +
                </button>
              </div>
              <div class="item-total">
                小计: ¥{{ item.totalPrice }}
              </div>
              <button 
                @click="removeFromCart(item.id)"
                class="btn btn-danger btn-small"
              >
                移除
              </button>
            </div>
          </div>
          
          <!-- 购物车总计 -->
          <div class="cart-summary">
            <div class="summary-row">
              <span>商品总数:</span>
              <span>{{ cartItemCount }} 件</span>
            </div>
            <div class="summary-row total">
              <span>总金额:</span>
              <span>¥{{ cartTotal }}</span>
            </div>
            <button 
              @click="handleCheckout"
              :disabled="checkoutStatus === 'pending'"
              class="btn btn-success btn-full"
            >
              {{ getCheckoutButtonText() }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 结账状态提示 -->
      <div v-if="checkoutStatus" class="checkout-status">
        <div :class="['status-message', `status-${checkoutStatus}`]">
          {{ getCheckoutStatusMessage() }}
        </div>
      </div>
    </div>
    
    <!-- 学习说明 -->
    <div class="explanation">
      <h3>🎯 Modules模块化学习要点：</h3>
      <div class="concept-grid">
        <div class="concept-item">
          <h4>命名空间 (Namespaced)</h4>
          <p>使用 <code>namespaced: true</code> 避免模块间命名冲突</p>
          <p>访问: <code>this.$store.state.cart.items</code></p>
        </div>
        <div class="concept-item">
          <h4>模块内通信</h4>
          <p>模块内的getters可以接收模块内的state和getters作为参数</p>
          <p>Actions可以访问模块内的state、getters、mutations</p>
        </div>
        <div class="concept-item">
          <h4>辅助函数映射</h4>
          <p>使用 <code>mapState('cart', ['items'])</code></p>
          <p>或 <code>...mapGetters('cart', ['cartTotal'])</code></p>
        </div>
        <div class="concept-item">
          <h4>模块化的优势</h4>
          <p>• 代码组织更清晰</p>
          <p>• 易于维护和扩展</p>
          <p>• 避免命名冲突</p>
          <p>• 支持模块复用</p>
        </div>
      </div>
      
      <div class="code-examples">
        <h4>🔧 关键代码模式：</h4>
        <div class="code-example">
          <h5>1. 模块定义</h5>
          <pre><code>export default {
  namespaced: true,
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}</code></pre>
        </div>
        <div class="code-example">
          <h5>2. 使用辅助函数</h5>
          <pre><code>computed: {
  ...mapState('cart', ['items']),
  ...mapGetters('cart', ['cartTotal'])
},
methods: {
  ...mapActions('cart', ['addToCart'])
}</code></pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'ShoppingCartExample',
  data() {
    return {
      selectedQuantities: {} // 存储用户选择的商品数量
    }
  },
  computed: {
    // 映射cart模块的状态和getters
    ...mapState('cart', ['checkoutStatus']),
    ...mapGetters('cart', [
      'cartItems', 
      'cartTotal', 
      'cartItemCount', 
      'availableProducts', 
      'isCartEmpty',
      'getProductById'
    ])
  },
  methods: {
    // 映射cart模块的actions
    ...mapActions('cart', [
      'addToCart', 
      'removeFromCart', 
      'updateCartItemQuantity', 
      'checkout'
    ]),
    
    // 获取用户选择的商品数量
    getSelectedQuantity(productId) {
      return this.selectedQuantities[productId] || 1
    },
    
    // 增加选择数量
    increaseQuantity(productId) {
      const current = this.getSelectedQuantity(productId)
      const product = this.getProductById(productId)
      if (current < product.inventory) {
        this.$set(this.selectedQuantities, productId, current + 1)
      }
    },
    
    // 减少选择数量
    decreaseQuantity(productId) {
      const current = this.getSelectedQuantity(productId)
      if (current > 1) {
        this.$set(this.selectedQuantities, productId, current - 1)
      }
    },
    
    // 添加商品到购物车
    async addToCart(productId) {
      const quantity = this.getSelectedQuantity(productId)
      const result = await this.$store.dispatch('cart/addToCart', { 
        id: productId, 
        quantity 
      })
      
      if (result.success) {
        // 重置选择数量
        this.$set(this.selectedQuantities, productId, 1)
        this.showMessage(result.message, 'success')
      } else {
        this.showMessage(result.message, 'error')
      }
    },
    
    // 更新购物车商品数量
    async updateItemQuantity(itemId, newQuantity) {
      if (newQuantity <= 0) {
        this.removeFromCart(itemId)
        return
      }
      
      const result = await this.updateCartItemQuantity({ 
        id: itemId, 
        quantity: newQuantity 
      })
      
      if (!result.success) {
        this.showMessage(result.message, 'error')
      }
    },
    
    // 检查是否可以增加数量
    canIncreaseQuantity(itemId, currentQuantity) {
      const product = this.getProductById(itemId)
      return product && currentQuantity < product.inventory
    },
    
    // 清空购物车
    clearCart() {
      if (confirm('确定要清空购物车吗？')) {
        this.$store.commit('cart/CLEAR_CART')
      }
    },
    
    // 处理结账
    async handleCheckout() {
      const result = await this.checkout()
      
      if (result.success) {
        this.showMessage(result.message, 'success')
        setTimeout(() => {
          this.$store.commit('cart/SET_CHECKOUT_STATUS', null)
        }, 3000)
      } else {
        this.showMessage(result.message, 'error')
        setTimeout(() => {
          this.$store.commit('cart/SET_CHECKOUT_STATUS', null)
        }, 3000)
      }
    },
    
    // 获取结账按钮文本
    getCheckoutButtonText() {
      switch (this.checkoutStatus) {
        case 'pending':
          return '结账中...'
        case 'success':
          return '结账成功'
        case 'failed':
          return '重新结账'
        default:
          return '立即结账'
      }
    },
    
    // 获取结账状态消息
    getCheckoutStatusMessage() {
      switch (this.checkoutStatus) {
        case 'pending':
          return '正在处理订单，请稍候...'
        case 'success':
          return '🎉 订单处理成功！感谢您的购买！'
        case 'failed':
          return '❌ 订单处理失败，请检查商品库存或稍后重试'
        default:
          return ''
      }
    },
    
    // 显示消息（简单实现）
    showMessage(message, type) {
      // 在实际应用中，这里可以使用更好的消息提示组件
      if (type === 'success') {
        alert('✅ ' + message)
      } else {
        alert('❌ ' + message)
      }
    }
  }
}
</script>

<style scoped>
.shopping-cart-example {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-container {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
  margin-bottom: 30px;
}

@media (max-width: 768px) {
  .cart-container {
    grid-template-columns: 1fr;
  }
}

.products-section {
  background: #fff;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.products-section h3 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.product-card {
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.product-info h4 {
  margin-bottom: 10px;
  color: #495057;
}

.product-price {
  font-size: 1.2rem;
  font-weight: bold;
  color: #e74c3c;
  margin-bottom: 5px;
}

.product-inventory {
  color: #6c757d;
  font-size: 0.9rem;
  margin-bottom: 15px;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.quantity-display {
  min-width: 30px;
  text-align: center;
  font-weight: bold;
}

.cart-section {
  background: #fff;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-header h3 {
  color: #2c3e50;
  margin: 0;
}

.empty-cart {
  text-align: center;
  padding: 40px 20px;
  color: #6c757d;
}

.cart-items {
  max-height: 500px;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  margin-bottom: 10px;
}

.item-info h4 {
  margin: 0 0 5px 0;
  color: #495057;
  font-size: 1rem;
}

.item-price {
  margin: 0;
  color: #6c757d;
  font-size: 0.9rem;
}

.item-controls {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity {
  min-width: 20px;
  text-align: center;
  font-weight: bold;
}

.item-total {
  font-weight: bold;
  color: #e74c3c;
}

.cart-summary {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #dee2e6;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-row.total {
  font-size: 1.1rem;
  font-weight: bold;
  color: #2c3e50;
  padding-top: 10px;
  border-top: 1px solid #dee2e6;
}

.checkout-status {
  grid-column: 1 / -1;
  margin-top: 20px;
}

.status-message {
  padding: 15px 20px;
  border-radius: 6px;
  text-align: center;
  font-weight: 500;
}

.status-pending {
  background: #cce5ff;
  color: #004085;
  border: 1px solid #b3d9ff;
}

.status-success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-failed {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-small {
  padding: 4px 8px;
  font-size: 0.8rem;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-full {
  width: 100%;
}

.explanation {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 12px;
  border-left: 5px solid #ffc107;
}

.explanation h3 {
  color: #2c3e50;
  margin-bottom: 20px;
}

.concept-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 25px;
}

.concept-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.concept-item h4 {
  color: #495057;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.concept-item p {
  color: #6c757d;
  font-size: 0.9rem;
  line-height: 1.5;
  margin: 5px 0;
}

.code-examples {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.code-examples h4 {
  color: #495057;
  margin-bottom: 15px;
}

.code-example {
  margin-bottom: 20px;
}

.code-example h5 {
  color: #6c757d;
  margin-bottom: 8px;
}

pre {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  border-left: 4px solid #007bff;
}

code {
  font-family: 'Courier New', monospace;
  color: #e83e8c;
  font-size: 0.9rem;
}
</style>